﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Imaging;

namespace GoodStuff.TestWeb
{
    public partial class TestImageCropping : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            btnCrop.Click += new EventHandler(btnCrop_Click);
        }

        void btnCrop_Click(object sender, EventArgs e)
        {
            System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("~/images/1680x1050_Zixpk_HD_Wallpaper_209.jpg"));

            var newImage = cropper1.PerformCrop(img, true);

            //save this image to the output folder, for demo only.
            string extension = ".png";
            string path = Server.MapPath("~/images/");
            string newFullPathName = System.IO.Path.Combine(path, "output" + extension);

            using (EncoderParameters encoderParameters = new EncoderParameters(1))
            {
                encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
                newImage.Save(newFullPathName, GetImageCodec(extension), encoderParameters);
            }
            newImage.Dispose();
        }

        /// <summary>
        /// Find the right codec
        /// </summary>
        /// <param name="extension"></param>
        /// <returns></returns>
        private static ImageCodecInfo GetImageCodec(string extension)
        {
            extension = extension.ToUpperInvariant();
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FilenameExtension.Contains(extension))
                {
                    return codec;
                }
            }
            throw new ArgumentException("No encoder available for " + extension);
        } 
    }
}